package com.kavin.rgb;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public abstract class CheckPermissionActivity extends AppCompatActivity {
    public final int REQUEST_PERMISSION_LOCATION = 10;
    public final String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        boolean noPermission = checkSelfPermission();
        if (noPermission) {
            requestPermissions();
        }
    }

    /**
     * 没有权限返回 true
     */
    public boolean checkSelfPermission() {
        for (String permission : permissions) {
            //如果权限没有授权
            boolean noPermission = ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED;
            // 没有权限
            if (noPermission) {
                return true;
            }
        }

        return false;
    }

    public void requestPermissions() {
        ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSION_LOCATION);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_LOCATION:
                boolean noPermission = checkSelfPermission();
                if (noPermission) {
                    onRequestPermissionsResultListener(requestCode, permissions, grantResults, true);
                } else {
                    onRequestPermissionsResultListener(requestCode, permissions, grantResults, false);
                }

                break;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    /**
     * noPermission == true 表示没有获取
     */
    abstract void onRequestPermissionsResultListener(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults, boolean noPermission);

}
